package filter;
/*
    date：
    topic：
    Filter要实现三个方法不然会报错，有 init，doFilter，destroy这三个方法
    doFilter是浏览器传过来的信息
*/
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

// url映射/*，给所有页面处理中文乱码      filterName 过滤器类名      urlPatterns /*所有的请求都经过过滤器
@WebFilter(filterName = "CharacterFilter",urlPatterns = "/*",initParams = {@WebInitParam(name="encoding",value = "utf-8")})
public class CharacterFilter implements Filter {//实现filter接口, 过滤器要实现Filter接口
    //字符编码
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取初始化参数
        encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (encoding!=null) {
            //设置request字符编码 请求
            servletRequest.setCharacterEncoding(encoding);
            //设置response字符编码 响应
            servletResponse.setContentType("text/html;charset="+encoding);
        }
        //传递给下一个过滤器
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        encoding=null;
    }
}

